package com.talent.jiwen.wrongbook;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.wrongbook.ErrorBookBean;
import com.talent.jiwen.http.result.wrongbook.ErrorListBean;
import com.talent.jiwen.http.result.tiku.Question;
import com.talent.jiwen.ui.widgets.LoadDialog;
import com.talent.jiwen.util.Constant;
import com.talent.jiwen.util.DateUtils;
import com.talent.jiwen.util.MyToast;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.wrongbook.data.WrongListData;
import com.talent.jiwen.wrongbook.data.WrongSingleData;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class WrongListActivity extends BaseActivity {
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private static final String PARAM_SUBJECT_ID = "param.subject.id";

    private String subjectId;

    private int startIndex  = 0;
    private List<WrongListData> dataList = new ArrayList<>();

    private boolean firstLoad = true;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_wrong_list;
    }

    @Override
    public String titleName() {
        return null;
    }

    @Override
    protected void initData() {
        setHeadVisibility(View.VISIBLE);

        subjectId = getIntent().getStringExtra(PARAM_SUBJECT_ID);

        LinearLayoutManager layoutManager = new LinearLayoutManager(WrongListActivity.this);
        recycleView.setLayoutManager(layoutManager);
        recycleView.setAdapter(new CommonAdapter<WrongListData>(WrongListActivity.this , R.layout.item_wrong_list , dataList){
            @Override
            protected void convert(ViewHolder holder, final WrongListData data, int position) {
                TextView contentTv = holder.getView(R.id.contentTv);
                contentTv.setText(data.getQuestion());

                String time = DateUtils.formatDate(new Date(data.getCreateTime()) , "yyyy/MM/dd HH:mm");
                holder.setText(R.id.timeTv , time);

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        WrongDetailActivity.startErrorBookSingleActivity(WrongListActivity.this,  data.getHomeworkId() , data.getHomeworkType() , data.getWrongSingleData());
                    }
                });
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                startIndex = 0 ;
                getData();
//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                startIndex ++;
                getData();
//                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });

        getData();
    }


    /**获取错题数据
     *
     */
    private void getData(){
        if (firstLoad){
            LoadDialog.show(this);
        }

        final Map<String, String> hashMap = new HashMap<>();
        hashMap.put("studentId", SPUtil.stringOut(SPConstant.USER_ID));
        hashMap.put("subjectId", subjectId);
        hashMap.put("homeworkType", "1");
        hashMap.put("startIndex", startIndex + "");

        Observable observable = ApiFactory.getEducationApiSingleton().getStudentWrongHomeworkList(SPUtil.stringOut(SPConstant.TOKEN), hashMap);

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<ErrorListBean>(this) {
                    @Override
                    protected void _onNext(ErrorListBean errorListBean) {

                        if (startIndex == 0){
                            dataList.clear();
//                            refreshLayout.finishRefresh();
                        }
//                        else{
//                            if (errorListBean.getList().size() < 10 || errorListBean.getList().size() == 0){
//                                refreshLayout.finishLoadMoreWithNoMoreData();
//                            }else{
//                                refreshLayout.finishLoadMore();
//                            }
//                        }

                        StringBuilder timuIds = new StringBuilder();
                        for(ErrorBookBean errorBookBean : errorListBean.getList()){
                            WrongListData data = new WrongListData();
                            data.setHomeworkId(errorBookBean.getHomeworkId());
                            data.setHomeworkType(errorBookBean.getHomeworkType());
                            data.setCreateTime(errorBookBean.getCreateTime());
                            data.setChapterName(errorBookBean.getChapterName());
                            WrongSingleData singleBean = new WrongSingleData();
                            singleBean.setWrongHomeworkInfo(errorBookBean);
                            data.setWrongSingleData(singleBean);
                            dataList.add(data);

                            timuIds.append(errorBookBean.getHomeworkId() + "");
                            timuIds.append(",");
                        }
                        if (timuIds.length() > 1) {
                            timuIds.deleteCharAt(timuIds.length() - 1);
                        }
                        getTimus(timuIds.toString());


                    }

                    @Override
                    protected void _onError(String message) {
                        MyToast.show(WrongListActivity.this , message);
                    }
                }
                , ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);
    }

    /**获取题目
     *
     * @param timuIds
     */
    private void getTimus(final String timuIds) {

        Observable observable = ApiFactory.getTiKuApiSingleton().getQuestionByIds(timuIds);

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<Question.DataBean>>(this) {
                    @Override
                    protected void _onNext(List<Question.DataBean> listData) {
                        getImage(listData);

                    }

                    @Override
                    protected void _onError(String message) {
                        MyToast.show(WrongListActivity.this , message);

                    }
                }
                , ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);
    }

    /**html转化为 text
     *
     * @param question
     */
    public void getImage(List<Question.DataBean> question) {
        Observable.just(question)
                .subscribeOn(Schedulers.io())
                .map(new Func1<List<Question.DataBean>, List<WrongListData>>() {
                    @Override
                    public List<WrongListData> call(List<Question.DataBean> question) {
                        for (int i = 0; i < question.size(); i++) {
                            Question.DataBean dataBean = question.get(i);
                            for(WrongListData wrongListData : dataList){
                                if (wrongListData.getHomeworkId() == dataBean.getTimu_id()){
                                    Spanned tm = Html.fromHtml(dataBean.getTmhtm(), Constant.mImgGetFormNetwork, null);
                                    wrongListData.setQuestion(tm);
                                    break;
                                }
                            }
                        }
                        return dataList;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List<WrongListData>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (firstLoad){
                    LoadDialog.dismiss(WrongListActivity.this);
                }

                firstLoad = false;
                showToast(e.getMessage());
            }

            @Override
            public void onNext(List<WrongListData> question) {
                if (firstLoad){
                    LoadDialog.dismiss(WrongListActivity.this);
                }
                firstLoad = false;

                if (startIndex == 0){
                    refreshLayout.finishRefresh();
                }else{
                    if (question.size() < 10 || question.size() == 0){
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }else{
                        refreshLayout.finishLoadMore();
                    }
                }

                if (question.size()>0) {
                    recycleView.getAdapter().notifyDataSetChanged();
                } else {
                    showToast(getString(R.string.no_result_data));
                }
            }

        });
    }


    /**启动该页面
     *
     * @param context
     * @param subjectId
     */
    public static void startWrongListActivity(Context context , String subjectId){
        Intent intent = new Intent();
        intent.setClass(context , WrongListActivity.class);
        intent.putExtra(PARAM_SUBJECT_ID , subjectId);
        context.startActivity(intent);
    }
}
